import axios,{ type InternalAxiosRequestConfig } from 'axios'
import { nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import router from '@/router'
import { throttle, getUrlIp } from '@/utils/index'
import { useStore } from '@/stores/index'

let baseurl = getUrlIp()
// 倒计时刷新错误弹窗
const timeInterval = throttle((msg:string) => {
  ElMessage({
    type: 'error',
    message: msg,
    duration: 5000
  })
}, 2000)

// 游戏配置页面 - 单独的axios请求
const service = axios.create({
  baseURL: baseurl,
  timeout: 30000, // 请求超时
  headers: {
    'content-type': 'application/json;charset=utf-8',
    'ngrok-skip-browser-warning': true
  }
})

// 取消请求（用于取消重复请求接口）
const pendingQueue = new Map()
const CancelToken = axios.CancelToken
// 判断请求是否在队列中，如果在就对队列中的该请求执行取消操作
const judgePendingFunc = function (config: InternalAxiosRequestConfig<any>) {
  if (pendingQueue.has(`${config.method}->${config.url}`)) {
    pendingQueue.get(`${config.method}->${config.url}`)() //注意这里的括号不要漏掉
  }
}
// 删除队列中对应已执行的请求
const removeResolvedFunc = function (config: InternalAxiosRequestConfig<any>) {
  if (pendingQueue.has(`${config.method}->${config.url}`)) {
    pendingQueue.delete(`${config.method}->${config.url}`)
  }
}

// 请求拦截
service.interceptors.request.use(
  (config) => {
    if (!config.data) {
      config.data = {} // 解决请求没有参数时添加不上Content-Type问题
    }
    // judgePendingFunc(config) //请求发起之前先调用removeResolvedFunc方法
    const token = sessionStorage.getItem('PGtoken') ? sessionStorage.getItem('PGtoken') : ''
    config.headers.Authorization = 'Bearer ' + token
    return config
  },
  (err) => {
    return Promise.reject(err)
  }
)

// 返回拦截
service.interceptors.response.use(
  (response: any) => {
    // removeResolvedFunc(response.config) // 调用removeResolvedFunc在队列中删除执行过的请求
    const res = response.data
    const indexStore = useStore()
    if (res.code == 1) {
      nextTick(() => {
        indexStore.setPageLoading(false)
        indexStore.setModuleLoading(false)
      })
      return res
    } else if (res.code == 10401 || res.code == 10403) {
      timeInterval(res.msg)
      localStorage.clear()
      sessionStorage.clear()
      router.replace({ path: '/login' })
    } else{
      timeInterval(res.msg)
      nextTick(() => {
        indexStore.setPageLoading(false)
        indexStore.setModuleLoading(false)
      })
      return Promise.reject(new Error(res.message || 'Error'))
    }
  },
  (error) => {
    const indexStore = useStore()
    nextTick(() => {
      indexStore.setPageLoading(false)
      indexStore.setModuleLoading(false)
    })
    timeInterval(error.msg?error.msg:'服务器网络繁忙，请刷新后重试！')
    return Promise.reject(error)
  }
)

export interface Res<T> {
  code: number
  msg: string
  data: T
}

export default <T = any>(req: any) => service<T, Res<T>>(req)
